package dao

import (
	"time"

	"github.com/astaxie/beego/orm"
	"learn-web/models"
)

type UserDao struct {
}

func (dao *UserDao) GetUsers(accountName, appName string, pageIndex, pageSize int64) (int64, []models.User, error) {
	dbOrm := orm.NewOrm()

	q := dbOrm.QueryTable("users")

	if accountName != "" {
		q = q.Filter("account_name__icontains", accountName)
	}
	if appName != "" {
		q = q.Filter("app_name__icontains", appName)
	}

	count, err := q.Count()
	if err != nil {
		return count, nil, err
	}

	var users []models.User
	q.Limit(pageSize, pageSize*(pageIndex-1)).All(&users)
	return count, users, nil
}

func (dao *UserDao) GetUser(id int64) (*models.User, error) {
	dbOrm := orm.NewOrm()

	var user models.User

	rs := dbOrm.Raw("select id,account_name,app_name,secret,qrcode,create_time from users where id=?", id)
	err := rs.QueryRow(&user)
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func (dao *UserDao) GetUser2(accountName, appName string) (*models.User, error) {
	dbOrm := orm.NewOrm()

	var user models.User

	rs := dbOrm.Raw("select id,account_name,app_name,secret,qrcode,create_time from users where account_name=? and app_name=?", accountName, appName)
	err := rs.QueryRow(&user)
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func (dao *UserDao) AddUser(user *models.User) error {
	dbOrm := orm.NewOrm()

	user.CreateTime = time.Now()

	rs := dbOrm.Raw("insert into users(account_name,app_name,create_time) values(?,?,?)",
		user.AccountName, user.AppName, user.CreateTime)
	result, err := rs.Exec()
	if err != nil {
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return err
	}
	user.Id = id

	return nil
}

func (dao *UserDao) UpdateUser(user *models.User) error {
	dbOrm := orm.NewOrm()

	user.CreateTime = time.Now()

	rs := dbOrm.Raw("update users set account_name=?,app_name=?,create_time=? where id=?",
		user.AccountName, user.AppName, user.CreateTime, user.Id)
	_, err := rs.Exec()
	if err != nil {
		return err
	}

	return nil
}

func (dao *UserDao) DeleteUser(id int64) error {
	dbOrm := orm.NewOrm()

	rs := dbOrm.Raw("delete from users where id=?", id)
	_, err := rs.Exec()
	if err != nil {
		return err
	}

	return nil
}

func (dao *UserDao) UpdateOTP(id int64, secret, qrcode string) error {
	dbOrm := orm.NewOrm()

	rs := dbOrm.Raw("update users set secret=?,qrcode=?,create_time=? where id=?", secret, qrcode, time.Now(), id)
	_, err := rs.Exec()
	if err != nil {
		return err
	}

	return nil
}
